from flask import Flask, jsonify, render_template, request
import pika

app = Flask(__name__)

# RabbitMQ配置
RABBITMQ_QUEUE = 'from_node2_to_node1'

# Flask路由
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/send', methods=['POST'])
def send_message():
    # 创建 RabbitMQ 连接和通道
    credentials = pika.PlainCredentials('admin', 'password')
    parameters = pika.ConnectionParameters('192.168.6.236', 5672, '/', credentials)
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()

    # 声明队列
    channel.queue_declare(queue=RABBITMQ_QUEUE)

    message = request.form['message']
    channel.basic_publish(exchange='', routing_key=RABBITMQ_QUEUE, body=message)

    # 关闭连接
    connection.close()

    return '', 204

@app.route('/messages', methods=['GET'])
def get_messages():
    # 创建 RabbitMQ 连接和通道
    credentials = pika.PlainCredentials('admin', 'password')
    parameters = pika.ConnectionParameters('192.168.6.236', 5672, '/', credentials)
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()

    # 声明队列
    channel.queue_declare(queue=RABBITMQ_QUEUE)

    method_frame, header_frame, body = channel.basic_get(queue=RABBITMQ_QUEUE, auto_ack=True)

    # 关闭连接
    connection.close()

    if method_frame:
        message = body.decode()
        print(message)
        return jsonify(message=message)
    else:
        return jsonify(message="No messages available")

if __name__ == '__main__':
    app.run(debug=True)
